import 'dart:io';

import 'package:app_installer/app_installer.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:my_app/utils/index.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class DownloadInstallPage extends StatefulWidget {
  const DownloadInstallPage({super.key});

  @override
  State<DownloadInstallPage> createState() => _DownloadInstallPageState();
}

class _DownloadInstallPageState extends State<DownloadInstallPage> {
  final necessaryPermissions = [
    Permission.storage,
  ];

  // final fileUrl = 'http://172.30.4.45:3000/OmoFun 1.0.7 .apk';
  final fileUrl = 'http://172.30.4.45:3000/藏龙小说.apk';
  String? filePath;

  Future<bool> checkPermission() async {
    final status = await Permission.storage.request();
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      return false;
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("下载APK并安装")),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(getProgressString(downloadRatio)),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: LinearProgressIndicator(
                value: downloadRatio,
                semanticsLabel: 'Linear progress indicator',
              )
            ),
            ElevatedButton(
              onPressed: () async {
                if (await checkPermission()) {
                  // downloadAndroid(fileUrl);
                  filePath = await downloadFile(fileUrl);
                  LogUtil.d(filePath);
                }
              },
              child: const Text("下载APK")
            ),
            ElevatedButton(
              onPressed: () async{
                if (await checkPermission() && filePath != null) {
                  AppInstaller.installApk(filePath!);
                }
              },
              child: const Text("安装APK")
            ),
            ElevatedButton(
              onPressed: () async {
                if (await checkPermission()) {
                  filePath = await downloadFile(fileUrl);
                  if (filePath != null) {
                    AppInstaller.installApk(filePath!);
                  }
                }
              },
              child: const Text("下载APK并安装")
            )
          ]
        ),
      ),
    );
  }
 
  //用分割URL来获取下载的APK名称
  String getFlieName(String url) {
    try {
      List<String> lstStr = url.split('/');
      return lstStr.last;
    } catch (e) {
      LogUtil.e("获取下载文件名错误：$e");
    }
    return "";
  }

  double dPercent = 0;
  bool downloadFinish = false;
 
  String getProgressString(double progress) {
    return '${(downloadRatio * 100).toStringAsFixed(2)}%';
  }

  CancelToken? token;
  double downloadRatio = 0;
  bool isDownloading = false;
  Future<String?> downloadFile(String path) async {
    token = CancelToken();
    String fileName = getFlieName(path);
    /// 创建存储文件
    Directory? storageDir = await getExternalStorageDirectory();
    String storagePath = storageDir!.path;

    String filePath = '$storagePath/$fileName';
    isDownloading = true;
    final response = await Dio().download(path, filePath, cancelToken: token,
        onReceiveProgress: (int received, int total) {
      if (total != -1) {
        if (!token!.isCancelled) {
          setState(() {
            downloadRatio = (received / total);
            if (downloadRatio == 1) {

              isDownloading = false;
            }
            if (downloadRatio > 0.95) {
              if (kDebugMode) {
                print(getProgressString(downloadRatio));
              }
            }
          });
        }
      } else {
        isDownloading = false;
        EasyLoading.showError('无法获取文件大小，下载失败!');
      }
    });
    if (response.statusCode == 200) {
      return Future.value(filePath);
    } else {
      return null;
    }
  }

}